package com.example.stray_animal_management_system.volunteer.controller;

import com.example.stray_animal_management_system.commonu.service.AnimalService;
import com.example.stray_animal_management_system.entity.Animal;
import com.example.stray_animal_management_system.entity.RescueStory;
import com.example.stray_animal_management_system.volunteer.service.RescueStoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: panpan
 * @time: 2025/10/26
 */
@RestController
@RequestMapping("/api/story")
@CrossOrigin
public class RescueStoryController {

    @Autowired
    private RescueStoryService storyService;

    @Autowired
    private AnimalService animalService;

    /** 查询所有故事（可带动物信息） */
    @GetMapping("/list")
    public Map<String, Object> listAll() {
        Map<String, Object> res = new HashMap<>();

        // 查询全部故事
        List<RescueStory> stories = storyService.list();

        // 查询对应动物信息

        List<Map<String, Object>> result = stories.stream().map(story -> {
            Map<String, Object> item = new HashMap<>();
            item.put("story", story);
            Animal animal = animalService.getById(story.getAnimalId());
            item.put("animal", animal);
            return item;
        }).collect(Collectors.toList());


        res.put("code", 200);
        res.put("msg", "查询成功");
        res.put("data", result);
        res.put("timestamp", System.currentTimeMillis());
        return res;
    }

    /** 根据动物ID查询该动物的所有故事 */
    @GetMapping("/animal/{animalId}")
    public Map<String, Object> listByAnimal(@PathVariable Integer animalId) {
        Map<String, Object> res = new HashMap<>();
        List<RescueStory> stories = storyService.lambdaQuery()
                .eq(RescueStory::getAnimalId, animalId)
                .list();

        res.put("code", 200);
        res.put("msg", "查询成功");
        res.put("data", stories);
        return res;
    }

    /**  新增故事 */
    @PostMapping("/add")
    public Map<String, Object> addStory(@RequestBody RescueStory story) {
        Map<String, Object> res = new HashMap<>();

        // 校验动物是否存在
        if (animalService.getById(story.getAnimalId()) == null) {
            res.put("code", 404);
            res.put("msg", "关联的动物不存在");
            return res;
        }

        story.setCreateTime(LocalDateTime.now());
        boolean saved = storyService.save(story);
        res.put("code", saved ? 200 : 500);
        res.put("msg", saved ? "故事添加成功" : "保存失败");
        return res;
    }

    /** 上传故事图片 */
    @PostMapping("/uploadPhoto")
    public Map<String, Object> uploadPhoto(@RequestParam("file") MultipartFile file) {
        Map<String, Object> res = new HashMap<>();
        if (file.isEmpty()) {
            res.put("code", 400);
            res.put("msg", "文件为空");
            return res;
        }

        String uploadDir = System.getProperty("user.dir") + "/uploads/story_photos/";
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();

        String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
        File dest = new File(uploadDir + fileName);

        try {
            file.transferTo(dest);
            String fileUrl = "http://localhost:8080/uploads/story_photos/" + fileName;
            res.put("code", 200);
            res.put("msg", "上传成功");
            res.put("url", fileUrl);
        } catch (IOException e) {
            res.put("code", 500);
            res.put("msg", "上传失败：" + e.getMessage());
        }
        return res;
    }
}
